package com.iot.lemon.web.biz;

import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import com.iot.lemon.model.TArea;
import com.iot.lemon.model.TBuilding;
import com.iot.lemon.model.THouse;
import com.iot.lemon.service.TAreaService;
import com.iot.lemon.service.TBuildingService;
import com.iot.lemon.service.THouseService;
import com.iot.lemon.util.UserUtil;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import top.ibase4j.core.base.BaseController;
import top.ibase4j.core.util.ExcelReaderUtil;
import top.ibase4j.core.util.InstanceUtil;
import top.ibase4j.core.util.WebUtil;

/**
 * <p>
 * 房屋  前端控制器
 * </p>
 *
 * @author ShenHuaJie
 * @since 2018-08-18
 */
@Controller
@RequestMapping("/house")
@Api(value = "房屋接口", description = "房屋接口")
public class THouseController extends BaseController<THouse, THouseService> {
    @Autowired
    private TAreaService areaService;
    @Autowired
    private TBuildingService buildingService;

    @RequiresPermissions("house.read")
    @RequestMapping(value = "/read/page")
    @ApiOperation(value = "查询房屋", produces = MediaType.APPLICATION_JSON_VALUE)
    public Object query(HttpServletRequest request) {
        Map<String, Object> param = WebUtil.getParameter(request);
        try {
            param.put("villageId", UserUtil.getMyVillageId());
        } catch (Exception e) {
        }
        List<Long> orgaIds = UserUtil.getMyOrgIds();
        if (orgaIds.size() > 1) {
            param.put("orgaIds", orgaIds);
        }
        return super.query(param);
    }

    @RequiresPermissions("house.read")
    @PutMapping(value = "/read/list")
    @ApiOperation(value = "查询房屋", produces = MediaType.APPLICATION_JSON_VALUE)
    public Object queryList(HttpServletRequest request) {
        Map<String, Object> param = WebUtil.getParameter(request);
        try {
            param.put("villageId", UserUtil.getMyVillageId());
        } catch (Exception e) {
        }
        List<Long> orgaIds = UserUtil.getMyOrgIds();
        if (orgaIds.size() > 1) {
            param.put("orgaIds", orgaIds);
        }
        return super.queryList(param);
    }

    @RequiresPermissions("house.read")
    @PutMapping(value = "/read/detail")
    @ApiOperation(value = "房屋详情", produces = MediaType.APPLICATION_JSON_VALUE)
    public Object get(HttpServletRequest request) {
        THouse param = WebUtil.getParameter(request, THouse.class);
        param.setOrgaId(UserUtil.getMyOrgaId());
        param.setVillageId(UserUtil.getMyVillageId());
        return super.get(param);
    }

    @PostMapping
    @RequiresPermissions("house.update")
    @ApiOperation(value = "修改房屋", produces = MediaType.APPLICATION_JSON_VALUE)
    public Object update(HttpServletRequest request) {
        THouse param = WebUtil.getParameter(request, THouse.class);
        param.setOrgaId(UserUtil.getMyOrgaId());
        param.setVillageId(UserUtil.getMyVillageId());
        return super.update(param);
    }

    @DeleteMapping
    @RequiresPermissions("house.delete")
    @ApiOperation(value = "删除房屋", produces = MediaType.APPLICATION_JSON_VALUE)
    public Object del(HttpServletRequest request) {
        THouse param = WebUtil.getParameter(request, THouse.class);
        return super.delete(param);
    }

    @PostMapping("/upload")
    @RequiresPermissions("house.update")
    @ApiOperation(value = "导入房屋", produces = MediaType.APPLICATION_JSON_VALUE)
    public Object upload(HttpServletRequest request) {
        CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(
            request.getSession().getServletContext());
        Map<String, Integer> resultMap = InstanceUtil.newHashMap();
        if (multipartResolver.isMultipart(request)) {
            Map<String, TArea> areaMap = InstanceUtil.newHashMap();
            Map<String, TBuilding> buildingMap = InstanceUtil.newHashMap();
            Long villageId = UserUtil.getMyVillageId();
            MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest)request;
            for (Iterator<String> iterator = multiRequest.getFileNames(); iterator.hasNext();) {
                String key = iterator.next();
                MultipartFile multipartFile = multiRequest.getFile(key);
                if (multipartFile != null) {
                    try {
                        List<String[]> list = ExcelReaderUtil.excelToArrayList(multipartFile.getOriginalFilename(),
                            multipartFile.getInputStream());
                        for (String[] v : list) {
                            TArea area = areaMap.get(v[3].trim());
                            if (area == null) {
                                area = new TArea().setAreaName(v[3].trim()).setVillageId(villageId);
                                List<TArea> areas = areaService.queryList(area);
                                if (!areas.isEmpty()) {
                                    area.setId(areas.get(0).getId());
                                    areaMap.put(v[3].trim(), area);
                                } else {
                                    continue;
                                }
                            }
                            TBuilding building = buildingMap.get(v[3].trim() + v[4].trim());
                            if (building == null) {
                                building = new TBuilding().setBuildingName(v[4].trim()).setAreaId(area.getId());
                                List<TBuilding> buildings = buildingService.queryList(building);
                                if (!buildings.isEmpty()) {
                                    building.setId(buildings.get(0).getId());
                                    buildingMap.put(v[3].trim() + v[4].trim(), building);
                                } else {
                                    continue;
                                }
                                THouse house = new THouse().setHouseNo(v[5].trim())
                                        .setBuildingId(buildings.get(0).getId());
                                List<THouse> houses = service.queryList(house);
                                if (!houses.isEmpty()) {
                                    house = houses.get(0);
                                }
                                house.setOwnerName(v[1].trim()).setOwnerCard(v[2].trim()).setOwnerPhone(v[6].trim());
                                super.update(house);
                                if (resultMap.get(area.getAreaName()) == null) {
                                    resultMap.put(area.getAreaName(), 0);
                                }
                                resultMap.put(area.getAreaName(), resultMap.get(area.getAreaName()) + 1);
                            }
                        }
                    } catch (Exception e) {
                        logger.error("", e);
                    }
                }
            }
        }
        StringBuilder sb = new StringBuilder();
        for (String area : resultMap.keySet()) {
            sb.append(area).append("导入房屋数据").append(resultMap.get(area)).append("条<br>");
        }
        return setSuccessModelMap(sb.toString());
    }
}
